package com.cqs.leetcode.offerII;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import static java.util.stream.Collectors.toList;

/**
 * 通过将字符串转化为数字 或运算
 * 通过&运算判断字符串是否重复
 */
public class OfferII007 {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                if (nums[left] + nums[right] + nums[i] == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[left++]);
                    list.add(nums[right--]);
                    result.add(list);
                    //跳过和num左指针相同的元素
                    while (left < right && nums[left - 1] == nums[left]) ++left;
                    while (left < right && nums[right] == nums[right + 1]) --right;
                } else if (nums[left] + nums[right] + nums[i] > 0) {
                    --right;
                } else {
                    ++left;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<int[]> list = new ArrayList<>();
        list.add(new int[]{-1, 0, 1, 2, -1, 4});
        list.add(new int[]{0, 2, -2, 0, 2});
        OfferII007 o = new OfferII007();
        list.forEach(new Consumer<int[]>() {
            @Override
            public void accept(int[] ints) {
                System.out.println(Arrays.stream(ints).boxed().collect(toList()) + "\t" + o.threeSum(ints));
            }
        });
    }
}
